package com.sea.data.controller;

import com.codecrane.core.util.DateUtils;
import com.codecrane.core.util.ExcelUtil;
import com.codecrane.core.web.Ajax;
import com.codecrane.core.web.AjaxReturn;
import com.codecrane.core.web.AjaxTableReturn;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sea.data.entity.SalesForecast;
import com.sea.data.entity.SalesStock;
import com.sea.data.service.SalesForecastService;
import com.sea.data.service.SalesStockService;
import com.sea.product.service.ChannelService;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping(value = "/sea/data/sales/stock")
public class SalesStockController {

    private List<String> header;

    @Autowired
    private SalesStockService salesStockService;
    @Autowired
    private ChannelService channelService;
    @Autowired
    private SalesForecastService salesForecastService;

    private List<Map<String, Object>> body;
    /**
     * 管理主页面
     * @param model
     * @return
     */
    @RequestMapping("/main")
    public String main(Model model) {
        //渠道
        model.addAttribute("channel", channelService.findByCnd(null));
        return "/sea/data/sales/stock/main";
    }

    @RequestMapping("/report/main")
    public String reportMain(Model model) {
        //渠道
        model.addAttribute("channel", channelService.findByCnd(null));
        return "/sea/data/sales/stock/report";
    }

    @RequestMapping("/getStockHeader")
    @ResponseBody
    public List<String> getStockHeader(){
        List<SalesForecast> salesDate = salesForecastService.findBySalesDate();
        List<SalesForecast> salesMonth = salesForecastService.groupBySalesMonth();
        List<String> list=new ArrayList<>();
        list.add("asin");
        list.add("listing");
        list.add("beginNumber");
        for(SalesForecast month:salesMonth){
            list.add(month.getSalesMonth());
        }

        list= DateUtils.getDays(list,salesDate.get(0).getSalesDate(),salesDate.get(salesDate.size()-1).getSalesDate());
        header=list;
        return list;
    }

    @RequestMapping("/getStockBody")
    @ResponseBody
    public List<Map<String, Object>> getStockBody(){


        List<String> pList = new ArrayList<>();
        List<String> mList=new ArrayList<>();
        List<SalesForecast> list = salesForecastService.findBySalesDate();
        for (SalesForecast salesForecast : list) {
              String  str = "(select d3.sales_sell_number from d_sales_forecast d3 where d3.sales_date='"+ salesForecast.getSalesDate() +"' and d3.sales_asin=d1.sales_asin and d3.sales_listing=d1.sales_listing) as '"+ salesForecast.getSalesDate() +"'";
            pList.add(str);
        }

        List<SalesForecast> monthList = salesForecastService.groupBySalesMonth();
        for (SalesForecast salesForecast : monthList) {
            String  str = "(select d3.sales_number from d_sales_forecast d3 where d3.sales_date='"+ salesForecast.getSalesMonth() +"-01'  and d3.sales_asin=d1.sales_asin and d3.sales_listing=d1.sales_listing) as '"+ salesForecast.getSalesMonth() +"'";
            mList.add(str);
        }

        List<Map<String, Object>> mapList = salesForecastService.findReportByListingAsin(pList,mList);
        body = mapList;
        return mapList;
    }

    @RequestMapping("/test")
    public String test() {
        //先查找Listing
        List<SalesForecast> list = salesForecastService.groupByListing();
        //查找日期
        List<SalesForecast> dateList = salesForecastService.groupBySalesDate();
        for(SalesForecast salesForecast:list){

            SalesStock salesStock=new SalesStock();
            salesStock.setStockListing(salesForecast.getSalesListing());
            Integer beginIndex=0;
            Integer endIndex=1;
            int i = dateList.size() % 7;

            int count = dateList.size() / 7;
            for(Integer k=0;k<count;k++){
                salesStock.setStockBegin(dateList.get(beginIndex).getSalesDate());
                beginIndex=beginIndex+7;
                salesStock.setStockEnd(dateList.get(7*endIndex-1).getSalesDate());
                endIndex=endIndex+1;
                salesStock.setStockDate(salesStock.getStockBegin()+"/"+salesStock.getStockEnd());
                salesStockService.save(salesStock);

                salesStock.setSalesNumber(salesForecastService.findBySalesNumber(salesStock.getStockBegin(), salesStock.getStockEnd(), salesStock.getStockListing()));
                salesStock.setStockProduceNumber(salesForecastService.findByProduceNumber(salesStock.getStockBegin(), salesStock.getStockEnd(), salesStock.getStockListing()));
                salesStock.setStockPhysicalNumber(salesForecastService.findByPhysicalNumber(salesStock.getStockBegin(), salesStock.getStockEnd(), salesStock.getStockListing()));
                salesStockService.usave(salesStock);
            }
            //判断一周是否正好被整除
            if(i!=0){
                salesStock.setStockBegin(dateList.get(dateList.size()-i).getSalesDate());
                salesStock.setStockEnd(dateList.get(dateList.size()-1).getSalesDate());
                salesStock.setStockDate(salesStock.getStockBegin()+"/"+salesStock.getStockEnd());
                salesStockService.save(salesStock);
                salesStock.setSalesNumber(salesForecastService.findBySalesNumber(salesStock.getStockBegin(), salesStock.getStockEnd(), salesStock.getStockListing()));
                salesStock.setStockProduceNumber(salesForecastService.findByProduceNumber(salesStock.getStockBegin(), salesStock.getStockEnd(), salesStock.getStockListing()));
                salesStock.setStockPhysicalNumber(salesForecastService.findByPhysicalNumber(salesStock.getStockBegin(), salesStock.getStockEnd(), salesStock.getStockListing()));
                salesStockService.usave(salesStock);
            }

        }
        return "/sea/data/sales/stock/main";
    }

    @ResponseBody
    @RequestMapping("/findByCnd")
    public AjaxTableReturn findByCnd(@RequestParam(value = "limit", defaultValue = "10") int pagesize,
                                     @RequestParam(value = "offset", defaultValue = "0") int start,
                                     SalesStock salesStock) {
        start = start > 0 ? start / pagesize + 1 : 1;
        PageHelper.startPage(start, pagesize);
        List<SalesStock> list = salesStockService.findByCnd(salesStock);
        PageInfo<SalesStock> page = new PageInfo<>(list);
        return Ajax.tableDataOk(page.getTotal(), page.getList());
    }


    /**
     * 导出数据
     * @param response
     * @return
     */
    @RequestMapping("/export")
    @ResponseBody
    public void exportResourceDo(HttpServletResponse response) {
        String[] title = new String [header.size()];
        for(int i=0;i<title.length;i++){
            title[i]=header.get(i);
        }
        String fileName = "报表" + DateUtils.dateToString(new Date(),"yyyyMMdd") + ".xls";
        String sheetName = "报表";
        String[][] content = new String[body.size()][title.length];
        for (int i = 0; i < body.size(); i++) {
            content[i] = new String[title.length];
            Map<String, Object> map = body.get(i);
            Iterator entries = map.entrySet().iterator();
            Integer j=0;
            while (entries.hasNext()) {
                Map.Entry entry = (Map.Entry) entries.next();
                Object key = (Object) entry.getKey();
                Object value = (Object) entry.getValue();
                for(int k=0;k<title.length;k++){
                    if((key+"").equals(title[k])){
                        content[i][k] = value+"";
                    }
                }
                j=j+1;
            }
        }
        //创建HSSFWorkbook
        HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, getTitle(title), content, null);
        //响应到客户端
        try {
            this.setResponseHeader(response, fileName);
            OutputStream os = response.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //发送响应流方法
    public void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            try {
                fileName = new String(fileName.getBytes(),"ISO8859-1");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            response.setContentType("application/octet-stream;charset=ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename="+ fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public String[] getTitle(String[] list){
        String[] newList=new String[list.length];
        for(int i=0;i<list.length;i++){
            String str=list[i];
            switch (str){
                case "asin":
                    newList[i]="ASIN";
                    break;
                case "listing":
                    newList[i]="Listing";
                    break;
                case "beginNumber":
                    newList[i]=("FBA库存");
                    break;

                default :
                    newList[i]=(str);
            }
        }
        return newList;
    }


}
